package com.neuqsoft.zwytj.demo.service;

import com.google.gson.Gson;
import com.neuqsoft.api.client.DefaultNeuqClient;
import com.neuqsoft.api.constant.NeuqConstants;
import com.neuqsoft.api.exception.NeuqApiException;
import com.neuqsoft.api.util.*;
import com.neuqsoft.commons.util.SMUtil;
import com.neuqsoft.zwytj.demo.config.RestTemplateConfig;
import com.neuqsoft.zwytj.demo.dto.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @Desc描述: <br>
 * @Author: zhangfuxing
 * @Date: 2022/3/23
 **/
@Service
public class DemoService {

    public static final String SIGN_QUESTION = "?";
    public static final String SIGN_AND = "&";
    public static final String SIGN_TYPE = "SM2";
    public static final String ENCRYPT_TYPE = "SM4";
    public static final String CHARSET_UTF8 = "UTF-8";

    private static final HostnameVerifier PROMISCUOUS_VERIFIER = (s, sslSession) -> true;

    public Object getTestFrocs(ParamSaveDTO dto) throws Exception {
        //演示环境禁用证书检查
//        final RestTemplate restTemplate = new RestTemplate();
//        restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
//            @Override
//            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
//                if (connection instanceof HttpsURLConnection) {
//                    ((HttpsURLConnection) connection).setHostnameVerifier(PROMISCUOUS_VERIFIER);
//                }
//                super.prepareConnection(connection, httpMethod);
//            }
//        });
        //演示环境新版禁用证书检查
        RestTemplate restTemplate = new RestTemplate(RestTemplateConfig.sslIgnoreFactory());
//        暂存接口地址
        String baseuUrl = dto.getBaseUrl();

        RequestParametersHolder holder = getRequestHolderWithSign(dto.getGetParams(),
                dto.getAppId(),
                "SM2",
                dto.getAppPrivateKey(),
                "SM4",
                dto.getEncryptKey(), null);
        try {
            String queryParamsString = WebUtils.buildQuery(holder.getQueryParams(), CHARSET_UTF8);
            String url = baseuUrl + SIGN_QUESTION + queryParamsString;
            System.out.println("调用前：：" + url);
            Object result = restTemplate.getForEntity(url, Object.class);
            System.out.println("修改");
            System.out.println("调用后：：" + new Gson().toJson(result));
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private RequestParametersHolder getRequestHolderWithSign(Map<String, String> params,
                                                             String appId,
                                                             String signType,
                                                             String privateKey,
                                                             String encryptType,
                                                             String encryptKey,
                                                             String accessToken) throws NeuqApiException {

        DefaultEncryptor encryptor = new DefaultEncryptor(encryptKey);
        DefaultSigner signer = new DefaultSigner(privateKey);

        RequestParametersHolder requestHolder = new RequestParametersHolder();
        NeuqHashMap queryParams = new NeuqHashMap();
        queryParams.put(NeuqConstants.APP_ID, appId);
        queryParams.put(NeuqConstants.SIGN_TYPE, signType);
        queryParams.put(NeuqConstants.ENCRYPT_TYPE, encryptType);
        queryParams.put(NeuqConstants.VERSION, "1.0");
        queryParams.put(NeuqConstants.ACCESS_TOKEN, accessToken);
        String queryContent = "";
        try {
            queryContent = com.neuqsoft.api.util.WebUtils.buildQuery(params, CHARSET_UTF8);
            queryParams.put(NeuqConstants.QUERY_CONTENT_KEY, encryptor.encrypt(queryContent, encryptType,
                    CHARSET_UTF8));
        } catch (IOException e) {
            throw new NeuqApiException(e);
        }
        queryParams.put(NeuqConstants.NONCESTR, UUIDUtils.uuid());
        queryParams.put(NeuqConstants.TIMESTAMP, DateTimeFormatter.ofPattern("yyyyMMddHHmmSS").format(LocalDateTime.now()));
        requestHolder.setQueryParams(queryParams);

        String signContent = NeuqSignature.getSignatureContent(requestHolder);
        queryParams.put(NeuqConstants.SIGN, signer.sign(appId, signContent, signType, CHARSET_UTF8));
        return requestHolder;
    }


    public Object decodeParamCert(ParamCertDecodeDTO dto){
        DefaultNeuqClient client = new DefaultNeuqClient(dto.getBaseUrl(),
                dto.getAppId(), dto.getAppPrivateKey(),
                dto.getNeuqPublicKey(), "SM2", dto.getEncryptKey(), "SM4");
        String url = dto.getBaseUrl();
        System.out.println("请求链接"+url);
        String map = client.get(url, null, null, String.class);
        System.out.println("请求结果"+map);
        return map;
    }


    public Object decodeSm4(DecodeSm4DTO dto){
        return SMUtil.sm4Decrypt(dto.getSm4Key(),dto.getContent());
    }

    public Object singleStatistic(SingleStatisticDTO dto){
        DefaultNeuqClient client = new DefaultNeuqClient(dto.getBaseUrl(),
                dto.getAppId(), dto.getAppPrivateKey(),
                dto.getNeuqPublicKey(), "SM2", dto.getEncryptKey(), "SM4");
        String url = dto.getBaseUrl();
        System.out.println("请求链接"+url);
        String map = client.postJson(url, null, dto.getReqData(),null, String.class);
        System.out.println("请求结果"+map);
        return map;
    }


    public Object batchStatistic(BatchStatisticDTO dto){
        DefaultNeuqClient client = new DefaultNeuqClient(dto.getBaseUrl(),
                dto.getAppId(), dto.getAppPrivateKey(),
                dto.getNeuqPublicKey(), "SM2", dto.getEncryptKey(), "SM4");
        String url = dto.getBaseUrl();
        System.out.println("请求链接"+url);
        String map = client.postJson(url, null, dto.getReqData(),null, String.class);
        System.out.println("请求结果"+map);
        return map;
    }

}
